package platform

import (
	"net/http"

	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	platformCommon "gitee.com/wangshh_123/cross-pay-go/src/platform/common"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/integration"
	hlpayServices "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay/services"
	photonpayModels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	photonpayServices "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/services"
	utilsCommon "gitee.com/wangshh_123/cross-pay-go/src/utils/common"

	"github.com/gin-gonic/gin"
)

// CardBinController 统一的卡BIN控制器
// 使用工厂模式处理不同平台的卡BIN查询
type CardBinController struct {
	platformManager *integration.PlatformManager
}

// NewCardBinController 创建卡BIN控制器实例
func NewCardBinController() *CardBinController {
	return &CardBinController{
		platformManager: integration.GetGlobalPlatformManager(),
	}
}

// GetCardBin 获取卡BIN信息
// 根据用户的平台类型自动选择对应的平台进行查询
func (c *CardBinController) GetCardBin(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		utilsCommon.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 如果是PhotonPay平台，直接调用PhotonPay服务返回原始格式
	if platformInfo.PlatformType == "photonpay" {
		c.getPhotonPayCardBin(ctx)
		return
	}

	// 如果是HlPay平台，调用HlPay服务但返回PhotonPay格式
	if platformInfo.PlatformType == "hlpay" {
		c.getHlPayCardBinAsPhotonPay(ctx)
		return
	}

	// 其他平台使用工厂模式处理请求
	request := &platformCommon.CardBinListRequest{
		PageIndex: 1,
		PageSize:  100,
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequest(ctx.Request.Context(), platformInfo.PlatformType, "card_bin_list", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "get_card_bin_failed", err)
		return
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformInfo.PlatformType,
		"data":     result,
	})
}

// getPhotonPayCardBin 直接获取PhotonPay的卡BIN信息，返回原始格式
func (c *CardBinController) getPhotonPayCardBin(ctx *gin.Context) {
	// 获取PhotonPay客户端
	photonpayClient, err := c.platformManager.GetPhotonPayClient()
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "photonpay_client_not_found", err)
		return
	}

	// 构建PhotonPay查询参数
	params := photonpayModels.CardBinQueryParams{
		// 可以根据需要添加过滤条件
	}

	// 直接调用PhotonPay服务
	result, err := photonpayServices.GetCardBin(ctx.Request.Context(), photonpayClient, params)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "get_photonpay_card_bin_failed", err)
		return
	}

	// 返回PhotonPay的原始响应格式
	utilsCommon.Success(ctx, gin.H{
		"platform": "photonpay",
		"data":     result,
	})
}

// getHlPayCardBinAsPhotonPay 获取HlPay的卡BIN信息，但返回PhotonPay格式
func (c *CardBinController) getHlPayCardBinAsPhotonPay(ctx *gin.Context) {
	// 获取HlPay客户端
	hlpayClient, err := c.platformManager.GetHlPayClient()
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "hlpay_client_not_found", err)
		return
	}

	// 调用HlPay服务，它已经返回PhotonPay格式
	result, err := hlpayServices.GetCardBin(ctx.Request.Context(), hlpayClient)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "get_hlpay_card_bin_failed", err)
		return
	}

	// 返回PhotonPay格式的响应
	utilsCommon.Success(ctx, gin.H{
		"platform": "hlpay",
		"data":     result,
	})
}

// GetCardBinByPlatform 根据指定平台获取卡BIN信息
// 允许管理员或高级用户查询指定平台的卡BIN信息
func (c *CardBinController) GetCardBinByPlatform(ctx *gin.Context) {
	// 从URL参数获取平台类型
	platformType := ctx.Param("platform")
	if platformType == "" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "platform_parameter_required", nil)
		return
	}

	// 构建统一的卡BIN查询请求
	request := &platformCommon.CardBinListRequest{
		PageIndex: 1,
		PageSize:  100,
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequest(ctx.Request.Context(), platformType, "card_bin_list", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "get_card_bin_failed", err)
		return
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformType,
		"data":     result,
	})
}

// GetCardBinComparison 获取两个平台的卡BIN对比信息
// 用于比较不同平台的卡BIN差异
func (c *CardBinController) GetCardBinComparison(ctx *gin.Context) {
	// 获取查询参数
	cardBin := ctx.Query("card_bin")
	if cardBin == "" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "card_bin_parameter_required", nil)
		return
	}

	// 构建统一的卡BIN查询请求
	request := &platformCommon.CardBinListRequest{
		PageIndex: 1,
		PageSize:  100,
	}

	// 获取支持的平台列表
	supportedPlatforms := c.platformManager.GetFactory().GetSupportedPlatforms()
	if len(supportedPlatforms) < 2 {
		utilsCommon.Error(ctx, http.StatusBadRequest, "insufficient_platforms_for_comparison", nil)
		return
	}

	// 并发查询多个平台的卡BIN信息
	type platformResult struct {
		platform string
		result   interface{}
		err      error
	}

	resultChan := make(chan platformResult, len(supportedPlatforms))

	// 为每个支持的平台启动一个goroutine进行查询
	for _, platform := range supportedPlatforms {
		go func(platformType string) {
			result, err := c.platformManager.HandleRequest(ctx.Request.Context(), platformType, "card_bin_list", request)
			resultChan <- platformResult{
				platform: platformType,
				result:   result,
				err:      err,
			}
		}(platform)
	}

	// 收集所有平台的结果
	comparison := gin.H{
		"card_bin": cardBin,
	}

	allFailed := true
	for i := 0; i < len(supportedPlatforms); i++ {
		platformResult := <-resultChan
		comparison[platformResult.platform] = gin.H{
			"success": platformResult.err == nil,
			"data":    platformResult.result,
			"error":   platformResult.err,
		}
		if platformResult.err == nil {
			allFailed = false
		}
	}

	// 如果所有平台都查询失败，返回错误
	if allFailed {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "all_platforms_failed", nil)
		return
	}

	utilsCommon.Success(ctx, comparison)
}

// GetSupportedPlatforms 获取支持的平台列表
func (c *CardBinController) GetSupportedPlatforms(ctx *gin.Context) {
	// 获取平台信息
	supportedPlatforms := c.platformManager.GetFactory().GetSupportedPlatforms()

	platforms := make([]gin.H, 0, len(supportedPlatforms))
	for _, platformID := range supportedPlatforms {
		platformInfo, err := c.platformManager.GetPlatformInfo(platformID)
		if err != nil {
			continue
		}

		platforms = append(platforms, gin.H{
			"platform":           platformID,
			"supported_features": platformInfo["supported_operations"],
			"config":             platformInfo["config"],
		})
	}

	utilsCommon.Success(ctx, gin.H{
		"platforms": platforms,
		"total":     len(platforms),
	})
}

// GetPlatformInfo 获取指定平台的详细信息
func (c *CardBinController) GetPlatformInfo(ctx *gin.Context) {
	platformType := ctx.Param("platform")
	if platformType == "" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "platform_parameter_required", nil)
		return
	}

	platformInfo, err := c.platformManager.GetPlatformInfo(platformType)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusNotFound, "platform_not_found", err)
		return
	}

	utilsCommon.Success(ctx, gin.H{
		"platform": platformType,
		"info":     platformInfo,
	})
}
